using System.Dynamic;
using System.Reflection;

namespace Core.Db.Helper;

public static class ObjectExtensions
{
    public static ExpandoObject ShapeData<TSource>(this TSource source, string? fields)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }

        //创建动态类型对象，创建数据塑性对象
        var dataShapedObject = new ExpandoObject();

        if (string.IsNullOrWhiteSpace(fields))
        {
            var propretyInfos = typeof(TSource).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            foreach (var propertyInfo in propretyInfos)
            {
                //获得对应属性的真实数据
                var propertyValue = propertyInfo.GetValue(source);
                ((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
            }
        }
        else
        {
            var fieldsAfterSplit = fields.Split(',');
            foreach (var filed in fieldsAfterSplit)
            {
                //去掉首尾多余的空格,获取属性名称
                var propertyName = filed.Trim();
                var propertyInfo = typeof(TSource).GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                if (propertyInfo == null)
                {
                    throw new Exception($"属性{propertyName}找不到 {typeof(TSource)}");
                }

                //获得对应属性的真实数据
                var propertyValue = propertyInfo.GetValue(source);
                ((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
            }
        }


        return dataShapedObject;
    }
}